package cn.tedu.boyou.comment.service.impl;

import cn.tedu.boyou.comment.domain.StrategyComment;
import cn.tedu.boyou.comment.repository.IStrategyCommentRepository;
import cn.tedu.boyou.comment.service.IStrategyCommentService;
import cn.tedu.boyou.common.query.StrategyCommentQuery;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IStrategyCommentRepository dao;


    public void save(StrategyComment comment) {
        comment.setCreateTime(new Date());
        dao.save(comment);
    }

    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        Query query = new Query();
        Criteria criteria = null;
        if(qo.getDestId() != -1){
            criteria = Criteria.where("destilId").is(qo.getDestId());
        }else {
            criteria = Criteria.where("detailId").ne(qo.getDestId());
        }

        query.addCriteria(criteria);
        /*下面可抄*/
        long total = mongoTemplate.count(query, StrategyComment.class);
        if(total == 0){
            return Page.empty();
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() -1, qo.getPageSize());
        query.with(pageable);
        Sort createTime = Sort.by(Sort.Direction.DESC, "createTime");
        query.with(createTime);
        List<StrategyComment> list = mongoTemplate.find(query, StrategyComment.class);

        return new PageImpl<StrategyComment>(list,pageable,total);
    }

    public boolean thumbUp(String toid, Long fromid) {
        /*StrategyComment comment = mongoTemplate.findById(toid, StrategyComment.class);*/
        Optional<StrategyComment> optional = dao.findById(toid);
        StrategyComment comment = optional.get();
        int thumbupnum = comment.getThumbupnum();
        List<Long> thumbuplist = comment.getThumbuplist();
        boolean flag = false;
        if(!thumbuplist.contains(fromid)){
            comment.setThumbupnum(thumbupnum +1);
            thumbuplist.add(fromid);
            flag = true;
        }else{
            comment.setThumbupnum(thumbupnum -1);
            thumbuplist.remove(fromid);
            flag = false;
        }
        dao.save(comment);
        return flag;
    }

}
